package com.sun.decrypt;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AesTest {
    private static final String ALGORITHM = "AES";//key长度16/24/32
    private static final String KEY = "1234567812345678";
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    @Test
    public void test1() {
        String str = "哈喽哈";
        String encrypt = encrypt(str);
        System.out.println("base64编码des加密后的结果 " + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("解码后的数据 " + decrypt);
    }

    /**
     * 加密
     *
     * @param str 待加密字符串
     * @return
     */
    public String encrypt(String str) {
        try {
            Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
            byte[] bytes = cipher.doFinal(str.getBytes(UTF8));
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param str 待解密字符串
     * @return
     */
    public String decrypt(String str) {
        try {
            Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
            byte[] bytes = cipher.doFinal(Base64.decodeBase64(str.getBytes(UTF8)));
            return new String(bytes, UTF8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Cipher getCipher(int i) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            SecretKey key = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
            cipher.init(i, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipher;
    }
}
